'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { 
  User, 
  Heart, 
  Package,
  Settings,
  BarChart3,
  Star
} from 'lucide-react'
import { UserProfile } from './user-profile'
import { MyTools } from './my-tools'
import { MyFavorites } from './my-favorites'
import { ProfileSettings } from './profile-settings'

type TabType = 'overview' | 'tools' | 'favorites' | 'settings'

export function ProfileDashboard() {
  const [activeTab, setActiveTab] = useState<TabType>('overview')

  const tabs = [
    { id: 'overview', label: '概览', icon: BarChart3 },
    { id: 'tools', label: '我的工具', icon: Package },
    { id: 'favorites', label: '我的收藏', icon: Heart },
    { id: 'settings', label: '设置', icon: Settings },
  ]

  const renderContent = () => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab setActiveTab={setActiveTab} />
      case 'tools':
        return <MyTools />
      case 'favorites':
        return <MyFavorites />
      case 'settings':
        return <ProfileSettings />
      default:
        return <OverviewTab setActiveTab={setActiveTab} />
    }
  }

  return (
    <div className="space-y-6">
      {/* 用户信息卡片 */}
      <UserProfile onEditProfile={() => setActiveTab('settings')} />

      {/* Tab导航 */}
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as TabType)}
                className={`flex items-center gap-2 py-2 px-1 border-b-2 font-medium text-sm ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <Icon className="h-4 w-4" />
                {tab.label}
              </button>
            )
          })}
        </nav>
      </div>

      {/* Tab内容 */}
      <div className="mt-6">
        {renderContent()}
      </div>
    </div>
  )
}

function OverviewTab({ setActiveTab }: { setActiveTab: (tab: TabType) => void }) {
  const { user } = useAuth()
  const [stats, setStats] = useState({
    totalTools: 0,
    publishedTools: 0,
    pendingTools: 0,
    totalFavorites: 0,
    totalReviews: 0,
    averageRating: 0
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (user) {
      fetchUserStats(user.id)
    }
  }, [user])

  const fetchUserStats = async (userId: string) => {
    try {
      setLoading(true)

      // 获取用户的工具
      const toolsParams = new URLSearchParams({
        userId: userId,
        includeOwn: 'true'
      })
      const toolsResponse = await fetch(`/api/tools?${toolsParams.toString()}`)
      const toolsResult = await toolsResponse.json()

      // 获取用户的收藏
      const favoritesResponse = await fetch('/api/favorites')
      const favoritesResult = await favoritesResponse.json()

      if (toolsResponse.ok && favoritesResponse.ok) {
        // 安全地访问数据，确保数据存在
        const toolsData = toolsResult?.data || []
        const favoritesData = favoritesResult?.data || []

        const userTools = Array.isArray(toolsData) ? toolsData.filter((tool: any) => tool?.userId === userId) : []
        const userFavorites = Array.isArray(favoritesData) ? favoritesData.filter((fav: any) => fav?.userId === userId) : []

        // 计算统计数据 - 安全地访问工具属性
        const publishedTools = userTools.filter((tool: any) => tool?.status === 'APPROVED')
        const pendingTools = userTools.filter((tool: any) => tool?.status === 'PENDING')

        // 计算总评价数和平均评分 - 安全地访问嵌套属性
        const totalReviews = userTools.reduce((sum: number, tool: any) => {
          const reviewCount = tool?._count?.reviews || 0
          return sum + reviewCount
        }, 0)

        // 计算加权平均评分 - 安全地访问工具属性
        let totalWeightedRating = 0
        let totalRatingCount = 0

        userTools.forEach((tool: any) => {
          if (tool) {
            const toolRating = tool.averageRating || 0
            const toolReviewCount = tool._count?.reviews || 0
            if (toolReviewCount > 0) {
              totalWeightedRating += toolRating * toolReviewCount
              totalRatingCount += toolReviewCount
            }
          }
        })

        const averageRating = totalRatingCount > 0 ? totalWeightedRating / totalRatingCount : 0

        setStats({
          totalTools: userTools.length,
          publishedTools: publishedTools.length,
          pendingTools: pendingTools.length,
          totalFavorites: userFavorites.length,
          totalReviews,
          averageRating
        })
      }
    } catch (error) {
      console.error('获取用户统计失败:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i} className="animate-pulse">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <div className="h-4 bg-gray-200 rounded w-20"></div>
              <div className="h-4 w-4 bg-gray-200 rounded"></div>
            </CardHeader>
            <CardContent>
              <div className="h-8 bg-gray-200 rounded w-12 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-16"></div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">发布的工具</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalTools}</div>
            <p className="text-xs text-muted-foreground">
              等待审核: {stats.pendingTools}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">收藏的工具</CardTitle>
            <Heart className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalFavorites}</div>
            <p className="text-xs text-muted-foreground">
              我的收藏
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">获得的评价</CardTitle>
            <Star className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalReviews}</div>
            <p className="text-xs text-muted-foreground">
              平均评分: {stats.averageRating.toFixed(1)}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已发布工具</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.publishedTools}</div>
            <p className="text-xs text-muted-foreground">
              公开可见
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 快速操作 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">快速操作</CardTitle>
            <CardDescription>
              管理您的工具和设置
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button className="w-full justify-start" onClick={() => window.location.href = '/tools/new'}>
              <Package className="h-4 w-4 mr-2" />
              发布新工具
            </Button>
            <Button variant="outline" className="w-full justify-start" onClick={() => setActiveTab('tools')}>
              <Settings className="h-4 w-4 mr-2" />
              管理我的工具
            </Button>
            <Button variant="outline" className="w-full justify-start" onClick={() => setActiveTab('favorites')}>
              <Heart className="h-4 w-4 mr-2" />
              查看我的收藏
            </Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">最近活动</CardTitle>
            <CardDescription>
              您的最新动态
            </CardDescription>
          </CardHeader>
          <CardContent>
            {stats.totalTools === 0 ? (
              <div className="text-center py-6">
                <Package className="h-8 w-8 text-gray-400 mx-auto mb-2" />
                <p className="text-sm text-gray-500">还没有发布任何工具</p>
                <Button size="sm" className="mt-2" onClick={() => window.location.href = '/tools/new'}>
                  立即发布
                </Button>
              </div>
            ) : (
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">总工具数</span>
                  <span className="font-medium">{stats.totalTools}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">已发布</span>
                  <span className="font-medium text-green-600">{stats.publishedTools}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">待审核</span>
                  <span className="font-medium text-yellow-600">{stats.pendingTools}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">总评价</span>
                  <span className="font-medium">{stats.totalReviews}</span>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
